package com.shareroad.dubboweb.frame.listener;

import java.io.File;
import java.io.FilenameFilter;
import java.net.MalformedURLException;
import java.util.StringTokenizer;

import javax.servlet.ServletContext;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;

import org.apache.catalina.loader.WebappClassLoader;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.shareroad.dubboweb.frame.dao.data.DubboWebData;
import com.shareroad.dubboweb.frame.util.JarUtil;
  
public class ExtClassLoadListener implements ServletContextListener {  
	private static final Logger logger = LoggerFactory.getLogger(ExtClassLoadListener.class);

    private static final String CONTEXT_PARAM_NAME_EXTLIBPATH = "dubboClientLocation";  
  
    @Override  
    public void contextInitialized(ServletContextEvent event) {  
        ServletContext context = event.getServletContext();
        String extlibs = context.getInitParameter(CONTEXT_PARAM_NAME_EXTLIBPATH);  
        logger.info("load extlibs path:"+extlibs);
        if (extlibs == null || extlibs.length() == 0) {
        	 logger.error("context-param<dubboClientLocation> is not set value!!!");
        	 return;
        } 
        addJar(extlibs); 
        parseJar(extlibs);
        
    }  
  
    @Override  
    public void contextDestroyed(ServletContextEvent event) {  
  
    }  
  
	synchronized private void addJar(String extlibs) {

		WebappClassLoader loader = (WebappClassLoader) getClass().getClassLoader();
		StringTokenizer st = new StringTokenizer(extlibs, ",");
		while (st.hasMoreTokens()) {
			String jarPath = st.nextToken();
			File jarDir = new File(jarPath);
			if (!jarDir.isDirectory()){
				continue;
			}
			File[] jarFiles = jarDir.listFiles(new JarFileNameFilter());
			for (File jarFile : jarFiles) {
				try {
					logger.info("addRepository:"+jarFile.getPath());
					loader.addRepository(jarFile.toURI().toURL().toString());
				} catch (MalformedURLException e) {
					e.printStackTrace();
					logger.error("add jar error,jarFile:"+jarFile.getPath(), e);
				}
			}
		}
	}
  
    class JarFileNameFilter implements FilenameFilter {  
        public boolean accept(File dir, String name) {  
            return name.toLowerCase().endsWith(".jar");  
        }  
    } 
    
	synchronized private void parseJar(String extlibs) {

		StringTokenizer st = new StringTokenizer(extlibs, ",");
		ClassLoader loader = JarUtil.getDubboWebClassLoader();
		while (st.hasMoreTokens()) {
				String jarPath = st.nextToken();
				File jarDir = new File(jarPath);
				for (File f : jarDir.listFiles(new JarFileNameFilter())) {
					logger.info("load jar:" + f.getPath());
					if (f.getName().endsWith(".jar")) {
						try {
							DubboWebData.addData(JarUtil.parseJar(f.getPath(),loader));
						} catch (Exception e) {
							e.printStackTrace();
							logger.error("parse dubbo client jar error,jarFile:"+f.getPath(), e);
						}
					}
				}
		}
	}
    
}